﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using ValidationFramework;
using ValidationFramework.Reflection;

namespace QSWcfServiceLibrary
{
    public static class WcfParameterValidationManager
    {
        public static void ThrowException(object target, Delegate methodDelegate, params object[] parameters)
        {
            var validationResults = ParameterValidationManager.Validate(target, methodDelegate, parameters);
            if (validationResults.Count > 0)
            {
                var concatenatedMessage = ResultFormatter.GetConcatenatedErrorMessages(validationResults);
                var dictionary = new Dictionary<string, List<string>>();
                foreach (var validationResult in validationResults)
                {
                    List<string> paramValidationResults;
                    var parameterDescriptor = (ParameterDescriptor)validationResult.InfoDescriptor;
                    if (!dictionary.TryGetValue(parameterDescriptor.Name, out paramValidationResults))
                    {
                        paramValidationResults = new List<string>();
                        dictionary.Add(parameterDescriptor.Name, paramValidationResults);
                    }
                    paramValidationResults.Add(validationResult.ErrorMessage);
                }
                var validationFaultException = new ValidationFaultException { ValidationErrors = dictionary };
                throw new FaultException<ValidationFaultException>(validationFaultException, concatenatedMessage);
            }
        }
    }
}
